package com.tg.app.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DeviceStateConstants;
import com.demo.view.TimeRuleView;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.media.source.impl.local.DeviceStoragePlayback;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tg.app.R;
import com.tg.app.activity.device.ui.cameraview.PlaybackViewListener;
import com.tg.app.helper.CameraViewHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.DeviceUIHelper;
import com.tg.app.util.LogUtils;
import com.tg.app.widget.ACLinearLayoutManager;
import com.tg.app.widget.ACRecyclerView;
import com.tg.app.widget.RecycleViewDivider;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;
import com.tg.message.adapter.MessagePlaybackAdapter;

import java.util.ArrayList;
import java.util.List;

public class ACPlayBackView extends LinearLayout implements View.OnClickListener {
    private static final String TAG = "ACPlayBackView";
    private TimeRuleView timeRuleView;

    private final List<DeviceStoragePlayback.Index> list = new ArrayList<>();


    private ACRecyclerView eventRecyclerView;
    private MessagePlaybackAdapter messagePlaybackAdapter;


    private TextView tvRuleTime, tvTime;
    private ACLinearLayoutManager layoutManager;
    private int mViewHeight;
    private Context mContext;
    private int eventDividerHeight;
    private Boolean mIsEventMove = false;
    private int playType = 0;
    private PlaybackViewListener playbackViewListener;
    private RelativeLayout indicatorLayout;
    private OnPlaybackListener onPlaybackListener;
    private int mOrientation = Configuration.ORIENTATION_PORTRAIT;
    private int eventIndex = -1;
    private boolean isStopScroll = false;
    private DeviceItem mDeviceItem;
    public boolean isEventForward = false;
    public boolean isLocal;
    private ACCameraShowErrorView mCameraShowErrorView;
    private View mLineView;
    public void setLocal(boolean local) {
        isLocal = local;
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            return false;
        }
    });

    public void setPlaybackViewListener(PlaybackViewListener playbackViewListener) {
        this.playbackViewListener = playbackViewListener;
    }

    public TimeRuleView getTimeRuleView() {
        return timeRuleView;
    }


    public ACPlayBackView(Context context) {
        super(context);
        init(context);
    }

    public ACPlayBackView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ACPlayBackView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void setOnPlaybackListener(OnPlaybackListener onClickListener) {
        onPlaybackListener = onClickListener;
        if (mCameraShowErrorView != null) {
            mCameraShowErrorView.setOnPlaybackListener(onPlaybackListener);
        }
    }

    public void setPlayType(int playType) {
        this.playType = playType;

    }

    private void init(final Context context) {
        mContext = context;
        View view = LayoutInflater.from(context).inflate(R.layout.layout_playback_view, null);
        addView(view);
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(layoutParams);
        timeRuleView = view.findViewById(R.id.playback_view_trvtime);
        tvRuleTime = view.findViewById(R.id.tv_playback_view_rule_time);
        tvTime = view.findViewById(R.id.tv_playback_view_time);
        mCameraShowErrorView = view.findViewById(R.id.ll_playback_view_cloud_service_none);
        indicatorLayout = view.findViewById(R.id.ll_playback_view_indicator);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        eventRecyclerView = view.findViewById(R.id.rv_playback_view_event_list);
        mLineView = view.findViewById(R.id.horizontal_line);
        layoutManager = new ACLinearLayoutManager(context) {

            @Override
            public void smoothScrollToPosition(RecyclerView recyclerView, int position, int snapPreference) {
                LinearSmoothScroller linearSmoothScroller =
                        new LinearSmoothScroller(recyclerView.getContext()) {
                            @Override
                            protected int getVerticalSnapPreference() {
                                return LinearSmoothScroller.SNAP_TO_START;
                            }
                        };
                linearSmoothScroller.setTargetPosition(position);
                startSmoothScroll(linearSmoothScroller);
            }
        };
        //设置布局管理器
        eventRecyclerView.setLayoutManager(layoutManager);
        eventRecyclerView.setItemAnimator(new DefaultItemAnimator());
        eventRecyclerView.setHasFixedSize(true);
        messagePlaybackAdapter = new MessagePlaybackAdapter(list);
        eventRecyclerView.setAdapter(messagePlaybackAdapter);
        mViewHeight = getResources().getDimensionPixelOffset(R.dimen.player_view_nav_height);
        setListener();
        tvRuleTime.setOnClickListener(this);
        eventRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (mIsEventMove && list.size() > 0) {
                        int positon = layoutManager.findFirstCompletelyVisibleItemPosition() - 1;
                        if (positon < 0) {
                            eventIndex = 0;
                        } else if (positon >= list.size()) {
                            eventIndex = list.size() - 1;
                        } else {
                            eventIndex = positon;
                        }
                        int time = getStartTime(eventIndex);
                        isEventForward = true;
                        TGLog.d(TAG, " onScrollStateChanged :" + DateUtil.formatTimeHHmmss(time));
                        timeRuleView.setCurTimeFrom(TimeRuleView.TIME_SET_FROM_MANUL);
                        timeRuleView.scrolltoTime(timeFiveLimit(time));
                        scrollEventTime(time, false, false);
                    }
                    mIsEventMove = false;
                    TGLog.d(TAG, "onScrollStateChanged SCROLL_STATE_IDLE");
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mIsEventMove){
                    if (playbackViewListener != null) {
                        playbackViewListener.onPlaybackPause();
                    }
                    setIndicatorLayout();
                }
            }
        });
    }

    public int getStartTime(int index) {

        if (index >= 0 && index < list.size()) {
            String start = DateUtil.getSecStrToTime(list.get(index).getStart());
            return DateUtil.getSecondDayHHMMSS(start);
        }
        return 0;
    }

    public int getEndTime(int index) {
        if (index >= 0 && index < list.size()) {
            String end = DateUtil.getSecStrToTime(list.get(index).getEnd());
            return DateUtil.getSecondDayHHMMSS(end);
        }
        return 0;
    }

    public void setTimePartList(List<TimeRuleView.TimePart> partList) {
        if (playType == CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD){
            if (timeRuleView.getVisibility() != View.VISIBLE) {
                timeRuleView.setVisibility(View.VISIBLE);
            }
        }

        if (partList != null && partList.size() > 0) {
            mCameraShowErrorView.setVisibility(GONE);
            if (timeRuleView != null){
                timeRuleView.setVisibility(VISIBLE);
            }
        }
        timeRuleView.setTimePartList(partList);
    }

    public void setBuyCloudServiceShow() {
        if (DeviceHelper.isCar(mDeviceItem)) {
            if (DeviceHelper.isCarExpired(mDeviceItem)){
                mCameraShowErrorView.setCarErrorInfo();
            }else{
                mCameraShowErrorView.setCarPrimaryErrorInfo();
            }

        } else if (DeviceHelper.isLamp(mDeviceItem)){
            hideErrorImageByMultiChannels();
            mCameraShowErrorView.setLampErrorInfo(DeviceHelper.hasLampServer(mDeviceItem));

        } else if (DeviceHelper.isLockBell(mDeviceItem) || DeviceHelper.isDoorBell(mDeviceItem) || DeviceHelper.isBirdFeeder(mDeviceItem)){
            mCameraShowErrorView.setPassiveDeviceErrorInfo();
        } else {
            hideErrorImageByMultiChannels();
            mCameraShowErrorView.setWifiErrorInfo();
        }
        if (timeRuleView != null){
            timeRuleView.setVisibility(GONE);
        }
        mCameraShowErrorView.setVisibility(VISIBLE);
        mLineView.setVisibility(GONE);
        indicatorLayout.setVisibility(GONE);
    }

    private void hideErrorImageByMultiChannels(){
        if (mDeviceItem!=null){
            DeviceFeature feature = DeviceFeatureObjectBox.queryDeviceFeature(mDeviceItem.uuid);
            if (CameraViewHelper.supportMultiChannelsPlaybackVertical(feature,getContext())){
                mCameraShowErrorView.hideErrorImage();
            }
        }
    }
    public void setBuySimCloudServiceShow() {
        mCameraShowErrorView.setVisibility(VISIBLE);
        if (timeRuleView != null){
            timeRuleView.setVisibility(GONE);
        }
        mLineView.setVisibility(GONE);
        indicatorLayout.setVisibility(GONE);
        mCameraShowErrorView.setSimCloudErrorInfo();
    }

    public void setExpiredSimCloudServiceShow() {
        mCameraShowErrorView.setVisibility(VISIBLE);
        if (timeRuleView != null){
            timeRuleView.setVisibility(GONE);
        }
        mLineView.setVisibility(GONE);
        indicatorLayout.setVisibility(GONE);
        mCameraShowErrorView.setSimCloudExpiredInfo();
    }

    public void setSimExpiredServiceShow() {
        mCameraShowErrorView.setVisibility(VISIBLE);
        if (timeRuleView != null){
            timeRuleView.setVisibility(GONE);
        }
        mLineView.setVisibility(GONE);
        indicatorLayout.setVisibility(GONE);
        mCameraShowErrorView.setSimExpiredInfo();
    }

    public void showSimExpiredService(){
        mCameraShowErrorView.setVisibility(GONE);
        if (timeRuleView != null){
            timeRuleView.setVisibility(VISIBLE);
        }
        mLineView.setVisibility(VISIBLE);
        indicatorLayout.setVisibility(VISIBLE);

    }


    public void setSdCardNone() {
        hideErrorImageByMultiChannels();
        mCameraShowErrorView.setSdCardNone();
        mLineView.setVisibility(GONE);
        if (CameraHub.getInstance().isEnableLocalApConnect()) {
            mCameraShowErrorView.setTextTip("");
        }
    }

    public void setSdCardVideoNone() {
        hideErrorImageByMultiChannels();
        mCameraShowErrorView.setVisibility(VISIBLE);
        if (timeRuleView != null){
            timeRuleView.setVisibility(GONE);
        }
        mCameraShowErrorView.setSdCardVideoNone();
        mLineView.setVisibility(GONE);
    }

    public void setDeviceItem(DeviceItem deviceItem) {
        mDeviceItem = deviceItem;
    }

    private DeviceUIHelper mDeviceUIHelper;

    public void setDeviceUIHelper(DeviceUIHelper deviceUIHelper) {
        mDeviceUIHelper = deviceUIHelper;
    }

    public void setBuyCloudServiceHidden(boolean has) {
        mCameraShowErrorView.setVisibility(GONE);
        if (timeRuleView != null){
            timeRuleView.setVisibility(VISIBLE);
        }
        boolean isScrolled = mDeviceUIHelper.isScrolled();
        boolean isWifiSdk = DeviceHelper.isWifiDevice(mDeviceItem) && playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD;
        boolean isSimCloud = DeviceHelper.is4GSupportCloud(mDeviceItem) && DeviceHelper.is4GHasCloud(mDeviceItem) && playType == CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD;
        if (has || mDeviceUIHelper.isScrolled() || isScrolled || isWifiSdk || isLocal || isSimCloud) {
            indicatorLayout.setVisibility(VISIBLE);
            mLineView.setVisibility(VISIBLE);
        } else {
            indicatorLayout.setVisibility(GONE);
            mLineView.setVisibility(GONE);
        }
    }

    public void showIndicatorLayout() {
        indicatorLayout.setVisibility(VISIBLE);
    }

    public void setRuleTime(String tvRuleTime) {
        this.tvRuleTime.setText(tvRuleTime);
        tvTime.setText(tvRuleTime);
    }

    public void setTimeVisible(int visible) {
        tvTime.setVisibility(visible);
    }

    public void setCurrentTime(int time, boolean updateTime) {
        this.tvRuleTime.setText(DateUtil.formatTimeHHmmss(time));
        timeRuleView.setCurrentTime(time, updateTime);
    }

    public void setCurrentTime(int time, boolean updateTime, final String from) {
        this.tvRuleTime.setText(DateUtil.formatTimeHHmmss(time));
        timeRuleView.setCurTimeFrom(from);
        timeRuleView.setCurrentTime(time, updateTime);

    }

    public void onConfigurationChanged(int orientation) {
        mOrientation = orientation;
        timeRuleView.onConfigurationChanged(orientation);
    }

    public void show() {
        TGLog.d(TAG, "show == 0");
        mOrientation = Configuration.ORIENTATION_PORTRAIT;
        Drawable drawable = getResources().getDrawable(R.mipmap.playback_view_indicator_arrow);
        tvRuleTime.setCompoundDrawables(null, null, drawable, null);
        tvRuleTime.setOnClickListener(this);
        eventRecyclerView.setVisibility(VISIBLE);
    }

    public void hide() {
        TGLog.d(TAG, "hide == 1");
        mOrientation = Configuration.ORIENTATION_LANDSCAPE;
        tvRuleTime.setCompoundDrawables(null, null, null, null);
        tvRuleTime.setOnClickListener(null);
        eventRecyclerView.setVisibility(GONE);
    }



    public void setEventList(List<DeviceStoragePlayback.Index> eventList) {
        this.list.clear();
        this.list.addAll(eventList);
        layoutManager.setScrollEnabled(true);
        isStopScroll = false;
        if (this.list.isEmpty()) {
            TGLog.d(TAG, "hide == 2");
            eventRecyclerView.setVisibility(GONE);
        } else {
            if (eventRecyclerView.getHeaderViewsCount() == 0) {
                setupEventListView();
            }
            TGLog.d(TAG, "mOrientation == " + mOrientation);
            eventRecyclerView.setVisibility(mOrientation == Configuration.ORIENTATION_PORTRAIT ? VISIBLE : GONE);
        }
        messagePlaybackAdapter.setCurrentPlayIndex(0);
        messagePlaybackAdapter.notifyDataSetChanged();
    }

    public void scrollStop() {
        isStopScroll = true;
        eventRecyclerView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 0, 0, 0));
        layoutManager.setScrollEnabled(false);
    }

    public void setupEventListView() {
        eventRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, ACLinearLayoutManager.VERTICAL));
        eventDividerHeight = getResources().getDimensionPixelOffset(R.dimen.playback_divider_height);
        int timeMarginTop = getResources().getDimensionPixelOffset(R.dimen.playback_time_margin_top);
        int headerHeight = timeMarginTop;
        eventRecyclerView.addHeaderView(makeView(headerHeight));

        int footerHeight = getHeight() - timeMarginTop;
        if (eventRecyclerView.getFooterViewsCount() == 0 && footerHeight > 500) {
            eventRecyclerView.addFooterView(makeView(footerHeight));
        }
    }

    public void addEventFooterView() {
        int timeMarginTop = getResources().getDimensionPixelOffset(R.dimen.playback_time_margin_top);
        int footerHeight = getHeight() - timeMarginTop;
        eventRecyclerView.addFooterView(makeView(footerHeight));
    }

    private LinearLayout makeView(int height) {
        LinearLayout linearLayout = new LinearLayout(getContext());
        linearLayout.setBackgroundColor(Color.TRANSPARENT);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
        linearLayout.setLayoutParams(layoutParams);
        return linearLayout;

    }

    private void scrollBoundary(int index) {
        if (eventIndex == -1) {
            eventRecyclerView.scrollToPosition(index);
        }
        TGLog.d("eventAdapter.getSelectedIndex() = " + messagePlaybackAdapter.getCurrentPlayIndex());
        if (messagePlaybackAdapter.getCurrentPlayIndex() != -1) {
            messagePlaybackAdapter.setCurrentPlayIndex(-1);
            messagePlaybackAdapter.notifyDataSetChanged();
        }
    }

    public void scrollEventTime(int time, boolean isClick, boolean isFromTimeChanged) {
        if (isStopScroll || eventRecyclerView.getVisibility() == GONE) {
            TGLog.d("isStopScroll:" + isStopScroll + " eventRecyclerView.getVisibility()==GONE " + eventRecyclerView.getVisibility());
            return;
        }

        tvRuleTime.setText(DateUtil.formatTimeHHmmss(time));
        if (list == null && list.size() == 0) {
            TGLog.d("eventList == null");
            return;
        }

        int index = getIndexEvent(time);
        if (!isFromTimeChanged && eventIndex == -1 && index >= 0 && index <= list.size() - 1) {
            eventIndex = isEventEndTimeOutEx(time, index, index + 1);
            TGLog.d(" == eventIndex == " + eventIndex);
        }
        int offset = 0;
        int firstIndex = layoutManager.findFirstVisibleItemPosition();
        int lastIndex = layoutManager.findLastVisibleItemPosition();
        TGLog.d("isClick = " + isClick + "size:" + list.size() + " firstIndex " + firstIndex + " lastIndex " + lastIndex + " index " + index + " offset: " + offset + " " + DateUtil.formatTimeHHmmss(time) + " eventIndex: " + eventIndex);
        if (eventIndex == -1 && (index <= 0 || index >= list.size())) {
            if (index >= list.size()) {
                index++;
            }
            scrollBoundary(index);
            return;
        }

        if (Math.abs(index - firstIndex) > 5) {
            TGLog.d("scrollToPosition " + index);
            TGLog.d(" time: " + DateUtil.formatTimeHHmmss(time));

            eventRecyclerView.scrollToPosition(index);
            final int showIndex = index;
            TGThreadPool.executeOnUiThreadDelayed(() -> layoutManager.smoothScrollToPositionWithOffset(eventRecyclerView, showIndex, LinearSmoothScroller.SNAP_TO_START, eventIndex != -1 ? offset / 2 : eventDividerHeight / 2), 100);

        } else {
            if (isClick) {
                int off = offset / 2;
                if (index == 0) {
                    off =  -mViewHeight/2 - eventDividerHeight;
                }
                layoutManager.smoothScrollToPositionWithOffset(eventRecyclerView, index, LinearSmoothScroller.SNAP_TO_START, off);
            } else {
                if (eventRecyclerView.getVisibility() == VISIBLE) {
                    if (index < list.size() || eventIndex != -1) {
                        boolean isEventIndex = false;
                        if (eventIndex >= 0) {
                            DeviceStoragePlayback.Index bean = eventIndex < list.size() ? list.get(eventIndex) : null;
                            if (bean != null && time + 10 >= timeFiveLimit(getStartTime(eventIndex)) && time <= getEndTime(eventIndex)) {
                                isEventIndex = true;
                                index = eventIndex;
                            } else {
                                eventIndex = -1;
                            }
                        }
                        int end = getEndTime(index);
                        if (time > end && !isEventIndex) {
                            layoutManager.smoothScrollToPositionWithOffset(eventRecyclerView, index, LinearSmoothScroller.SNAP_TO_START, eventDividerHeight / 2);
                            index = -1;
                        } else {
                            int off = offset / 2;
                            if (index == 0) {
                                off =  -mViewHeight/2 - eventDividerHeight;
                            }
                            TGLog.d("scrollToPosition111x " + index);
                            layoutManager.smoothScrollToPositionWithOffset(eventRecyclerView, index, LinearSmoothScroller.SNAP_TO_START, eventIndex == -1 ? eventDividerHeight / 2 : off);
                        }
                    } else {
                        layoutManager.smoothScrollToPositionWithOffset(eventRecyclerView, lastIndex, LinearSmoothScroller.SNAP_TO_START, 0);
                    }
                }
            }
        }

        TGLog.d("scrollToPosition111x eventInde99  " + eventIndex);
        setEventSelectedIndex(eventIndex == -1 ? -1 : index);
    }

    private void setEventSelectedIndex(int index) {
        if (messagePlaybackAdapter.getCurrentPlayIndex() != index) {
            messagePlaybackAdapter.setCurrentPlayIndex(index);
            messagePlaybackAdapter.notifyDataSetChanged();
        }
    }

    private int getIndexEvent(int time) {
        int index = 0;
        for (; index < list.size(); index++){
            int start = timeFiveLimit(getStartTime(index));
            if (time >= start) {
                break;
            }
        }
        return index;
    }

    private int timeFiveLimit(int time) {
        int modSec = time % 5;//留下多少秒
        return time - modSec;
    }

    public int isEventEndTimeOut(int time) {
        int index = -1;
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                long start = getStartTime(i);
                long end = getEndTime(i);
                if (timeFiveLimit((int) start) <= time && time <= end) {
                    index = i;
                    break;
                }
            }
        }
        return index;
    }

    public int isEventEndTimeOutEx(int time, int first, int end) {
        int index = -1;
        if (list.size() > 0) {
            first = Math.max(first - 1, 0);
            end = Math.min(end, list.size() - 1);
            for (int i = first; i <= end; i++) {
                DeviceStoragePlayback.Index eventMessage = null;
                if (i >= 0 && i < list.size()) {
                    eventMessage = list.get(i);
                }
                if (eventMessage != null && getStartTime(i) - 5 <= time && time <= getEndTime(i)) {
                    index = i;
                    break;
                }
            }
        }
        return index;
    }

    private void setIndicatorLayout() {
        if (indicatorLayout.getVisibility() != VISIBLE) {
            indicatorLayout.setVisibility(VISIBLE);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setListener() {
        timeRuleView.setOnTimeChangedListener(new TimeRuleView.OnTimeChangedListener() {
            @Override
            public boolean canScrolled() {
                return onPlaybackListener != null && onPlaybackListener.canScrolled();
            }

            @Override
            public void onScrolled(int newTimeValue) {
                if (playbackViewListener != null) {
                    playbackViewListener.onPlaybackPause();
                }
                if (mDeviceItem != null && mDeviceItem.is_open != DeviceStateConstants.DEVICE_OPEN && playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
                    onPlaybackListener.onDeviceOff();
                    return;
                }
                boolean hasServe = DeviceHelper.hasServe(mDeviceItem);
                mDeviceUIHelper.setIsScrolled(true);
                TGLog.d("onScrolled == ", "hasserver = " + hasServe);
                if (hasServe || playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
                    setIndicatorLayout();
                    String newTimeStr = DateUtil.formatTimeHHmmss(newTimeValue);
                    setRuleTime(newTimeStr);
                    if (playbackViewListener != null) {
                        playbackViewListener.onTimeScrolled(newTimeStr);
                    }
                } else if (onPlaybackListener != null) {
                    onPlaybackListener.onNoServe();
                }
            }

            @Override
            public void onTimeChanged(int newTimeValue) {
                TGLog.d("onTimeChanged0:" + newTimeValue);
                TGLog.trace();
                mDeviceUIHelper.setIsScrolled(true);
                if (mDeviceItem != null && mDeviceItem.is_open != DeviceStateConstants.DEVICE_OPEN && playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
                    TGLog.d("onTimeChanged1:" + newTimeValue);
                    onPlaybackListener.onDeviceOff();
                    return;
                }
                if (DeviceHelper.hasServe(mDeviceItem) || DeviceHelper.isWifiDevice(mDeviceItem) && playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD || isLocal) {
                    setIndicatorLayout();

                    if (playbackViewListener != null) {
                        playbackViewListener.onPlayTime(newTimeValue, timeRuleView.isFromAuto());
                    }
                    eventIndex = isEventEndTimeOut(newTimeValue);
                    int curTimeValue = newTimeValue;
                    if (playType == CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD) {
                        newTimeValue = DateUtil.getTimeFiveSec(newTimeValue);
                    }

                    String timeStr = DateUtil.formatTimeHHmmss(newTimeValue);
                    TGLog.d("onTimeChanged3:" + newTimeValue + ", eventIndex = " + eventIndex + ", timeStr = " + timeStr);
                    setRuleTime(timeStr);
                    TGLog.d("onTimeChanged4:" + eventIndex);
                    if (list.size() > 0) {
                        TGLog.d("onTimeChanged6:" + eventIndex);
                        scrollEventTime(curTimeValue, false, true);
                    }
                } else if (onPlaybackListener != null) {
                    TGLog.d("onTimeChanged11:" + newTimeValue);
                    onPlaybackListener.onNoServe();
                }

            }
        });
        messagePlaybackAdapter.setOnMessageItemListener(position -> {
            messagePlaybackAdapter.setCurrentPlayIndex(position);
            mHandler.removeCallbacksAndMessages(null);
            if (playbackViewListener != null) {
                playbackViewListener.onPlay(position);
            }
            if (position >= 0 && position < list.size()) {
                int time = getStartTime(position);
                isEventForward = true;
                timeRuleView.setCurTimeFrom(TimeRuleView.TIME_SET_FROM_MANUL);
                timeRuleView.scrolltoTime(time);
                eventIndex = position;
                scrollEventTime(time, true, false);
            }
        });


        eventRecyclerView.setOnTouchListener((view, motionEvent) -> {
            if (onPlaybackListener != null && !onPlaybackListener.canScrolled()) {
                return false;
            }
            int action = motionEvent.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    break;
                case MotionEvent.ACTION_MOVE:
                    mIsEventMove = true;
                    break;
                case MotionEvent.ACTION_UP:
                    LogUtils.matTrackCustomKVEvent(mContext, "play_back", "PBD");
                    break;
            }
            return false;
        });
    }

    @Override
    public void onClick(View view) {
        if (onPlaybackListener == null || !onPlaybackListener.canScrolled()) return;
        if (view.getId() == R.id.tv_playback_view_rule_time) {
            onPlaybackListener.onTimeChangedClick(tvRuleTime.getText().toString().trim());
        }
    }


    public interface OnPlaybackListener {
        void onBuyClick();

        void onNoServe();

        void onTimeChangedClick(String time);

        void onDeviceOff();

        boolean canScrolled();
    }
}
